package org.example.springoauth2.securitycommon.config.authenticate.grant.tt;

import org.example.springoauth2.securitycommon.constants.SecurityConstants;
import org.example.springoauth2.securitycommon.util.SecurityUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author hzq
 * @since 2021-09-12
 */
public class TtAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter {


    public TtAuthenticationProcessingFilter() {
        super(new AntPathRequestMatcher(SecurityConstants.TT_LOGIN, "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {

        // 可能系统中存在多个 抖音小程序配置 多租户的场景
        // 得到抖音小程序 appId 在系统中切换到对应的抖音小程序配置
        String appId = SecurityUtil.obtainAppId(request);

        // 通过code 获取 openid
        // 这里应该通过code和抖音小程序配置 去抖音服务器换取openid
        String code = SecurityUtil.obtainCode(request);

        // 伪造openid
        String openid = "tt_openid_" + code;

        TtAuthenticationToken token = new TtAuthenticationToken(openid);

        token.setDetails(authenticationDetailsSource.buildDetails(request));

        // 找对应的 token 提供者 去认证
        return this.getAuthenticationManager().authenticate(token);
    }
}
